package com.ruoyi.controller;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.domain.Article;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.domain.History;
import com.ruoyi.service.IHistoryService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 历史Controller
 * 
 * @author ya
 * @date 2025-08-17
 */
@RestController
@RequestMapping("/history/history")
public class HistoryController extends BaseController
{
    @Autowired
    private IHistoryService historyService;

    @Autowired
    private FileStorageService fileStorageService;


    /**
     * 图片路径
     */
    @Anonymous
    @PostMapping("/imgPath/{id}")
    public AjaxResult imgPath(@PathVariable Long id, @RequestParam("imgPath") MultipartFile imgPath) throws Exception {
        try {
            // 检查文件是否为空
            if (imgPath.isEmpty()) {
                return AjaxResult.error("上传文件为空");
            }

            // 获取 base-path
            String basePath = "historyImgPath";

            // 指定oss保存文件路径
            String objectName = basePath + LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd")) + "/" + imgPath.getOriginalFilename();
            // 上传图片，成功返回文件信息
            FileInfo fileInfo = fileStorageService.of(imgPath).setPath(objectName).upload();

            // 设置返回结果
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", fileInfo.getUrl());
            ajax.put("fileName", fileInfo.getUrl());
            ajax.put("newFileName", fileInfo.getUrl());
            ajax.put("originalFilename", imgPath.getOriginalFilename());

            // 创建Article对象并设置ID和filePath
            History history = new History();
            history.setId(id);
            history.setImg(fileInfo.getUrl());

            // 更新数据库中的filePath字段
            historyService.updateHistory(history);

            return ajax;

        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 查询历史列表
     */
//    @PreAuthorize("@ss.hasPermi('history:history:list')")
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(History history)
    {
        startPage();
        List<History> list = historyService.selectHistoryList(history);
        return getDataTable(list);
    }

    /**
     * 导出历史列表
     */
    @PreAuthorize("@ss.hasPermi('history:history:export')")
    @Log(title = "历史", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, History history)
    {
        List<History> list = historyService.selectHistoryList(history);
        ExcelUtil<History> util = new ExcelUtil<History>(History.class);
        util.exportExcel(response, list, "历史数据");
    }

    /**
     * 获取历史详细信息
     */
    @PreAuthorize("@ss.hasPermi('history:history:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(historyService.selectHistoryById(id));
    }

    /**
     * 新增历史
     */
    @PreAuthorize("@ss.hasPermi('history:history:add')")
    @Log(title = "历史", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody History history)
    {
        return toAjax(historyService.insertHistory(history));
    }

    /**
     * 修改历史
     */
    @PreAuthorize("@ss.hasPermi('history:history:edit')")
    @Log(title = "历史", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody History history)
    {
        return toAjax(historyService.updateHistory(history));
    }

    /**
     * 删除历史
     */
    @PreAuthorize("@ss.hasPermi('history:history:remove')")
    @Log(title = "历史", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(historyService.deleteHistoryByIds(ids));
    }
}
